import { defineStore } from 'pinia'
// 导入请求工具
import request from '@/utils/request'

interface User {
  id: number
  name: string
  email: string
  role: string
  identity?: string
  identityName?: string
  avatar?: string
}

export const useUserStore = defineStore('user', {
  state: () => ({
    user: null as User | null,
    isLoggedIn: false,
    token: '',
    _initialized: false // 标记是否已初始化
  }),

  getters: {
    userName: (state) => state.user?.name || '',
    userRole: (state) => state.user?.role || '',
    isAdmin: (state) => state.user?.role === 'admin'
  },

  actions: {
    login(userData: User, token: string) {
      this.user = userData
      this.token = token
      this.isLoggedIn = true
      localStorage.setItem('token', token)
      localStorage.setItem('user', JSON.stringify(userData))
    },

    logout() {
      this.user = null
      this.token = ''
      this.isLoggedIn = false
      localStorage.removeItem('token')
      localStorage.removeItem('user')
    },

    updateProfile(profileData: Partial<User>) {
      if (this.user) {
        this.user = { ...this.user, ...profileData }
        localStorage.setItem('user', JSON.stringify(this.user))
      }
    },

    // 初始化用户状态（从localStorage恢复）
    initUserState() {
      const token = localStorage.getItem('token')
      const userStr = localStorage.getItem('user')
      
      if (token && userStr) {
        try {
          this.token = token
          this.user = JSON.parse(userStr)
          this.isLoggedIn = true
        } catch (error) {
          console.error('恢复用户状态失败:', error)
          this.logout()
        }
      }
    },
    
    // 从服务器获取最新用户信息
    async fetchUserInfo() {
      try {
        // 在实际项目中，这里应该调用真实的API获取用户信息
        // 现在使用模拟数据
        const response = await request.get('/api/user/info')
        
        // 如果使用模拟数据，可以直接返回
        if (process.env.NODE_ENV === 'development' && !response) {
          // 模拟数据，实际项目中移除
          const mockUser: User = {
            id: 1,
            name: '张三',
            email: 'zhangsan@example.com',
            role: 'user',
            identityName: '学生',
            avatar: 'https://via.placeholder.com/100'
          }
          this.user = mockUser
          localStorage.setItem('user', JSON.stringify(mockUser))
          this.isLoggedIn = true
          return mockUser
        }
        
        // 处理真实API响应
        if (response && response.data) {
          this.user = response.data
          localStorage.setItem('user', JSON.stringify(response.data))
          this.isLoggedIn = true
          return response.data
        }
        return null
      } catch (error) {
        console.error('获取用户信息失败:', error)
        this.logout()
        throw error
      }
    }
  }
})